package com.xin.libandroidpaysocial.share;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xin.libandroidpaysocial.Loading;

import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by user on 2017/11/23.
 * 功能描述：第三方分享
 */

public class ShareUtils {
    public static ShareUtils.ShareCallBack shareCallBack;

    private static void log(String s) {
        Log.e(ShareUtils.class.getSimpleName(), s);
    }

    public static void initQQ(String appKey) {
        Constant.QQ_AppKey = appKey;
    }

    public static void initWeiXin(String appId) {
        Constant.WX_AppID = appId;
    }

    public static void init(Activity context) {

    }

    public static void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, new IUiListener() {
            @Override
            public void onComplete(Object o) {
                log("onComplete() called with: o = [" + o + "]");
            }

            @Override
            public void onError(UiError uiError) {
                log("onError() called with: uiError = [" + uiError + "]");
            }

            @Override
            public void onCancel() {
                log("onCancel() called");
            }
        });
    }

    public static void onNewIntent(Intent intent) {
    }


    /**
     * 微信 分享 回调 在WXEntryActivity类
     *
     * @param context
     * @param shareData
     */
    public static void wx(final Activity context, final ShareData shareData, final int scene, final ShareCallBack callBack) {
        final IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.WX_AppID);
        api.registerApp(Constant.WX_AppID);
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context, "未安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        final Dialog dialog = Loading.showProgressDialog(context);
        new Thread() {
            @Override
            public void run() {
                final byte[] imgData = getImgData(context.getApplicationContext(), shareData.getShare_image());
                context.runOnUiThread(() -> {
                    dialog.dismiss();
                    wx2(shareData, imgData, scene, callBack, api);
                });

            }
        }.start();


    }

    /**
     * @param appId
     * @param path
     * @param shareUrl 可为空
     * @return
     */
    public static WXMiniProgramObject getWXMiniProgramObject(String appId, String path, String shareUrl) {
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = shareUrl; // 兼容低版本的网页链接
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
        miniProgramObj.userName = appId;     // 小程序原始id
        miniProgramObj.path = path;            //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        return miniProgramObj;
    }

    /**
     * @param shareData
     * @param imgData   图片的二进制
     * @param scene
     * @param callBack
     * @param api
     */
    private static void wx2(ShareData shareData, byte[] imgData, int scene, ShareCallBack callBack, IWXAPI api) {
        ShareUtils.shareCallBack = callBack;
        WXMediaMessage.IMediaObject mediaObject = shareData.getMediaObject();
        if (mediaObject == null) {
            mediaObject = new WXWebpageObject(shareData.getShare_url());
        }
        WXMediaMessage msg = new WXMediaMessage(mediaObject);
        msg.thumbData = imgData;
        msg.title = shareData.getShare_title();
        msg.messageAction = shareData.getShare_url();
        msg.description = shareData.getShare_desc();

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = scene;
        boolean b = api.sendReq(req);
        log("wx2() called with: result = [" + b + "]");

    }

    /**
     * @param context
     * @param shareData 有可能是本地路径 图片地址 或资源id
     *                  从地址中获得图片的二进制
     * @return
     */
    private static byte[] getImgData(Context context, String shareData) {
        Bitmap imgBt = getImgBt(context, shareData, true);
        if (imgBt != null) {
            return getThumb(imgBt);
        }
        return new byte[0];
    }

    /**
     * 获得bitmap
     *
     * @param context
     * @param share_image
     * @param b           是否压缩
     * @return
     */
    private static Bitmap getImgBt(Context context, String share_image, boolean b) {
        Bitmap bmp = null;
        if (share_image != null) {
            if (share_image.matches("\\d*")) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getResources().getDrawable(Integer.parseInt(share_image));
                bmp = bitmapDrawable.getBitmap();
            } else {
                try {
                    if (share_image.startsWith("http")) { /*网络地址*/
                        bmp = BitmapFactory.decodeStream(new URL(share_image).openStream());
                    } else {   /*本地路径*/
                        bmp = BitmapFactory.decodeFile(share_image);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (bmp == null) {
            return null;
        }
        if (b && (bmp.getWidth() > 120 || bmp.getHeight() > 120)) { /*长或宽大于120时 才压缩*/
            Bitmap mBp = Bitmap.createScaledBitmap(bmp, 120, 120, true);
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle(); //此句造成的以上异常
            }
            return mBp;
        } else {
            return bmp;
        }
    }

    /**
     * 图片获得byte
     *
     * @param bmp
     * @return
     */
    private static byte[] getThumb(Bitmap bmp) {
        if (bmp == null || bmp.isRecycled()) {
            return new byte[0];
        }
        int maxkb = 30 * 1024; /*32K*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        int options = 90;
        while (output.toByteArray().length > maxkb && options != 10) {
            output.reset(); //清空output
            bmp.compress(Bitmap.CompressFormat.JPEG, options, output);//这里压缩options%，把压缩后的数据存放到output中
            options -= 10;
        }
        bmp.recycle();
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * qq 分享
     *
     * @param context
     * @param qzone   true 空间 false 发
     * @param qqData
     */
    public static void qq(Activity context, ShareData qqData, boolean qzone, final ShareCallBack callBack) {
        Tencent tencent = Tencent.createInstance(Constant.QQ_AppID, context);
        IUiListener uiListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                log("onComplete() called with: o = [" + o + "]");
                if (callBack != null) {
                    callBack.onComplete();
                }
            }

            @Override
            public void onError(UiError uiError) {
                log("onError() called with: uiError = [" + uiError + "]");
                if (callBack != null) {
                    callBack.onError();
                }
            }

            @Override
            public void onCancel() {
                log("onCancel() called");
                if (callBack != null) {
                    callBack.onCancel();
                }
            }
        };
        Bundle params = new Bundle();
        if (qzone) {
            ArrayList<String> listImgs = new ArrayList<String>();
            if (qqData.getShare_image().startsWith("http")) {
                listImgs.add(qqData.getShare_image());
            }
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, qqData.getShare_title());
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, qqData.getShare_desc());
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, qqData.getShare_url());
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, listImgs);
            params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, qqData.getApp_name());
            tencent.shareToQzone(context, params, uiListener);
        } else {
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, qqData.getShare_title());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, qqData.getShare_desc());
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, qqData.getShare_url());
            if (qqData.getShare_image().startsWith("http")) {
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, qqData.getShare_image());
            }
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, qqData.getApp_name());
            tencent.shareToQQ(context, params, uiListener);

        }
    }

    public static interface ShareCallBack {
        public void onComplete();

        public void onError();

        public void onCancel();

    }

    public static class SimpleShareCallBack implements ShareCallBack {
        @Override
        public void onComplete() {

        }

        @Override
        public void onError() {

        }

        @Override
        public void onCancel() {

        }
    }

}
